package treetool

import (
	"go-admin-auth/app/models"
	"strings"
)

type OrgTreeNode struct {
	models.TOrganization
	Child []*OrgTreeNode `json:"child"`
}

type orgTree struct {
	MenuList []models.TOrganization
	Tree     *OrgTreeNode
}

func initOrgTree(tr *OrgTreeNode, menuList []models.TOrganization) {
	// 把菜单中等于tree.id的都取出来
	for _, v := range menuList {
		if v.ParentId == tr.Id {
			subTreeNode := &OrgTreeNode{TOrganization: v}
			tr.Child = append(tr.Child, subTreeNode)
		}
	}

	for _, subTree := range tr.Child {
		initOrgTree(subTree, menuList)
	}
}

func orgSelectOptionList(s *[]models.TOrganization, tr *OrgTreeNode, level int) {
	if level != -1 {
		prefixStr := strings.Repeat(" ", level*6)
		prefixStr += "└"
		tr.Name = prefixStr + tr.Name
		*s = append(*s, tr.TOrganization)
	}

	for _, v := range tr.Child {
		orgSelectOptionList(s, v, level+1)
	}
}

func NewOrgTree(orgList []models.TOrganization, treeRootId int) *orgTree {
	tTree := &OrgTreeNode{}
	tTree.Id = treeRootId

	initOrgTree(tTree, orgList)

	mTree := &orgTree{MenuList: orgList, Tree: tTree}
	return mTree
}

func (m *orgTree) GetTree() *OrgTreeNode {
	return m.Tree
}

func (m *orgTree) GetSelectOptions() []models.TOrganization {
	optionList := make([]models.TOrganization, 0, len(m.MenuList))
	orgSelectOptionList(&optionList, m.Tree, -1)
	return optionList
}